<template>
  <div class="index" @contextmenu.prevent.capture>
    <Header class="header"></Header>
    <el-row class="body">
      <el-col :span="4" v-loading="menuLoading" element-loading-text="正在获取菜单信息..."
        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.7)">
        <MenuTree class="menu" :menus="menus" :menuLevel="0"></MenuTree>
      </el-col>
      <el-col :span="20">
        <el-row class="content">
          <el-tabs v-model="thisTab" type="card" closable @tab-remove="removeTab" @tab-click="clickTab">
            <el-tab-pane :key="item.name" v-for="(item, index) in tabs" :label="item.title" :name="item.name">
              {{ item.content }}
            </el-tab-pane>
          </el-tabs>
          <router-view v-if="isRouterAlive" @getMenuTree="getMenuTree"></router-view>
          <!-- <router-view v-loading="$store.state.loading_flag"></router-view> -->
        </el-row>
      </el-col>
    </el-row>

    <div class="rightMenu">
      <ul>
        <li @click="removeTab(rightMenuPath)">关闭</li>
        <li @click="cloneOtherTabs(rightMenuPath)">关闭其他选项卡</li>
        <li @click="cloneTabsOnThsleft(rightMenuPath)">关闭左侧选项卡</li>
        <li @click="cloneTabsOnThsRight(rightMenuPath)">关闭右侧选项卡</li>
      </ul>
    </div>
  </div>
</template>

<script>
//使用懒加载模式导入组件
const Header = () => import("./Common/Header");
const MenuTree = () => import("./Common/MenuTree/index.vue");

export default {
  name: "Home",
  components: {
    Header,
    MenuTree,
  },
  data() {
    return {
      // 当前路由，即当前选择页面
      thisTab: this.$route.path,
      // 打开的标签页
      tabs: [],
      // 菜单数据
      menus: [],
      // 加载菜单loading开关
      menuLoading: false,
      // 当前右击菜单操作的对象
      rightMenuPath: "",
      isRouterAlive: true,
    };
  },
  beforeCreate(){
    // let socket;
    // let token = sessionStorage.getItem("token");
    // let webSocket_base_url = process.env.VUE_APP_WEBSOCKET_BASE_URL != '/' ? process.env.VUE_APP_WEBSOCKET_BASE_URL : "wss://" + window.location.host;
    // let socketUrl = webSocket_base_url + "/socket/im?token=" + token

    // if(typeof(WebSocket) === "undefined"){
    //   console.log("您的浏览器不支持WebSocket");
    // }else{
    //   socket = new WebSocket(socketUrl);
    //   socket.onopen = function() {
    //     console.log("websocket已打开");
    //     //socket.send("这是来自客户端的消息" + location.href + new Date());
    //   };
    //   //获得消息事件
    //   socket.onmessage = function(msg) {
    //     //发现消息进入    开始处理前端触发逻辑
    //     let data = msg.data;
    //     if(data === "ping"){
    //       console.log("server: " + data);
    //     }else{
    //       console.log(data);
    //     }
    //   };
    //   //关闭事件
    //   socket.onclose = function() {
    //     console.log("websocket已关闭");
    //   };
    //   //发生了错误事件
    //   socket.onerror = function() {
    //     console.log("websocket发生了错误");
    //   }
    // }
    // // webSocket 30s心跳保持
    // setInterval(()=>{
    //   let message = "ping";
    //   console.log("client: " + message);
    //   socket.send(message);
    // }, 30000);
  },
  beforeUnmount() {
    //页面卸载时去除监听 防止占用资源
    document.body.removeEventListener('click', function(){
      let rightMenu = document.querySelector(".rightMenu");
      if(rightMenu){
        rightMenu.style.display = "none";
      }
    })
  },
  mounted() {
    this.getPermissions(this.$route.path)
    this.getMenuTree();
    //监听全页面，如果有点击就隐藏右击菜单
    document.body.addEventListener('click', function(){
      let rightMenu = document.querySelector(".rightMenu");
      if(rightMenu){
        rightMenu.style.display = "none";
      }
    })
  },
  watch: {
    // 监听路由变化，切换选项卡
    $route(to, form) {
      this.reload();
      this.getPermissions(to.path)
      if (this.checkTabs(to.path)) {
        this.pushTabs(this.menus, to.path);
      }
      this.thisTab = to.path
    }
  },
  methods: {
    // 在路由改变的时候，请求页面的按钮权限，存入vuex中
    getPermissions(menuRouter){
      this.$api.menu.getPermissions({menuRouter: menuRouter}).then(res=>{
        if(res.code == 200){
          this.$store.state.permissions = res.data
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    reload(){
      this.isRouterAlive = false;
      this.$nextTick(()=>{
        this.isRouterAlive = true;
      })
    },
    // 关闭其他选项卡
    cloneOtherTabs(name){
      this.cloneTabsOnThsRight(name);
      this.cloneTabsOnThsleft(name);
    },
    // 关闭右侧选项卡
    cloneTabsOnThsRight(name){
      let index = undefined;
      for (let i = 0; i < this.tabs.length; i++) {
        if (this.tabs[i].name == name) {
          index = i;
        }
      }
      let len = this.tabs.length;
      this.tabs.splice(index + 1, len - 1 - index)
      this.$router.push({ path: name });
    },
    // 关闭左侧选项卡
    cloneTabsOnThsleft(name){
      let index = undefined;
      for (let i = 0; i < this.tabs.length; i++) {
        if (this.tabs[i].name == name) {
          index = i;
        }
      }
      this.tabs.splice(0, index)
      this.$router.push({ path: name });
    },
    // 设置标签右击事件
    setRightClick() {
      //获取tabs的子dom列表
      let tabDom = document.querySelectorAll(".el-tabs__item");
      // 循环配置右击事件
      tabDom.forEach(e => {
        //触发右击事件的方法
        e.oncontextmenu = (el) => {
          if (el.button == 2) {
            //设置点击的tab的path 用于操作标签
            this.rightMenuPath = el.target.id.substring(4)
            //去掉浏览器默认事件
            el.preventDefault()
            //获取当前鼠标坐标来设置菜单栏的位置
            let rightMenu = document.querySelector(".rightMenu");
            rightMenu.style.top = event.clientY + "px";
            rightMenu.style.left = event.clientX + "px";
            //显示菜单栏
            rightMenu.style.display = "block";
          }
        }
      });
    },
    // 点击选项卡时触发，跳转至选项卡对应路由
    clickTab(e) {
      this.$router.push({ path: e.name });
    },
    // 关闭选项卡时触发回调
    removeTab(name) {
      let index = undefined;
      for (let i = 0; i < this.tabs.length; i++) {
        if (this.tabs[i].name == name) {
          index = i;
        }
      }
      let lastTab = this.tabs[index - 1];
      if (lastTab == undefined) {
        lastTab = this.tabs[index + 1];
      }
      if (lastTab == undefined) {
        this.$message.warning("最后一个标签页不可关闭")
        return
      }
      this.tabs.splice(index, 1)
      if (this.thisTab == name) {
        this.$router.push({ path: lastTab.name });
      }
    },
    // 请求菜单数据
    getMenuTree() {
      this.menuLoading = true;
      this.$api.menu.getMenuTree().then((res) => {
        if (res.code == 200) {
          this.menus = res.data;
          this.tabs = [];
          this.pushTabs(res.data, this.$route.path)
          this.menuLoading = false;
        }
      });
    },
    // 添加标签页
    pushTabs(menus, path) {
      menus.forEach(menu => {
        if (menu.menuRouter == path) {
          let tab = {
            name: menu.menuRouter,
            title: menu.menuName
          }
          this.tabs.push(tab);
          setTimeout(this.setRightClick,500);
        } else {
          this.pushTabs(menu.childMenus, path)
        }
      })
    },
    // 选项卡发现改变时触发
    checkTabs(path) {
      let flag = true;
      this.tabs.forEach(tab => {
        if (tab.name == path) {
          flag = false
        }
      })
      return flag
    }
  },
};
</script>

<style lang="less" scoped>
.index {
  width: 100%;

  .header {
    height: 60px;
    border-bottom: 1px solid #ccc;
    box-sizing: border-box;
  }

  .body {
    width: 100%;
    .menu {
      margin: 0;
      padding: 10px 0;
      border-right: 1px solid rgba(0, 0, 0, 0.1);
      height: calc(100vh - 60px);
      position: relative;
      z-index: 98;
      overflow-y: auto;
      overflow-x: hidden;
      box-sizing: border-box;
    }

    .content {
      width: 100%;
      height: calc(100vh - 60px);
      padding: 30px 50px;
      background: rgb(255, 255, 255);
      overflow-y: auto;
      overflow-x: hidden;
      box-sizing: border-box;
    }
  }

  .rightMenu{
    width: auto;
    height: auto;
    box-sizing: border-box;
    // border: 1px solid black;
    box-shadow: 0px 0px 5px #82cbff;
    border-radius: 10px;
    background: rgb(250,250,250);
    background: rgb(255,255,255);
    position: fixed;
    top: 10px;
    left: 40px;
    z-index: 9999;
    display: none;
    ul{
      list-style: none;
      li{
        font-size: 14px;
        color: rgb(175,175,175);
        
        padding: 10px 20px;
        // border-bottom: 1px solid #ccc;
        cursor: pointer;
      }
      li:hover{
        color: rgb(0,0,0);
        color: rgb(64,158,255);
        background-color: rgb(236,245,255);
      }
    }
  }
}
</style>